/*
    Copyright (c) Guangzhou Data Control Network Technology Co., Ltd. All rights reserved.
    Licensed under the MIT License.
    function: 渲染各类页面的js
    contact:dcdev_founder@foxmail.com
*/

function render_somthing_on_click(that, id, index) {
    var _this = window[`${id}_config`];
    // 点击回调
    if (_this.config.callback.click) {
        var res = {
            node: that,
            key: $(that).data("key"),
            index: index,
            value: _this.all_data[index],
        };
        _this.config.callback.click(res);
    }
}
function render_somthing() {
    var that;
    // 相关功能函数
    {
        render_somthing.prototype.func_expression_counting_value = function () {

        }
        render_somthing.prototype.func_on_change_input_value = function (_this, value) {
            // 将数值写入文本框
            $($(_this).parent()[0].children[1].children[0]).val(value);
            // 获取li_function.item_amount中的字段函数配置信息
            var li_function = window[`_dc_${$(_this).attr("key")}_render_data_`].li_config
                .li_function[$(_this).attr("li_function_index")];
            // 获得计算表达式
            var expression = li_function.expression.replace(/#{/, "row_data['").replace(/}/, "']").replace(
                "^{value}", value);
            // 获得在数据集中的index
            var index = parseInt($(_this).attr("index"));
            // 获得该行数据
            var row_data = window[`_dc_${$(_this).attr("key")}_render_data_`].data_fetched.page_data[index];
            var expression_value;
            var expression_array = [];
            try {
                expression_value = eval(expression);
                if (li_function.toFixed) {
                    expression_value = expression_value.toFixed(li_function.toFixed);
                    expression_array = expression_value.split(".");
                }
            } catch (error) { }

            if (window[li_function.items.on_change_value]) {
                row_data._dc_values_ ? null : row_data._dc_values_ = null;
                // 所选择行的索引
                row_data._dc_index = index;
                // 所输入的数量值
                row_data._dc_input_value = value;
                // 表达式计算之后的值
                row_data._dc_expression_value_ = expression_value;
                // 有小数点
                if (expression_array.length > 1) {
                    row_data._dc_expression_int_value_ = expression_array[0];
                    row_data._dc_expression_float_value_ = expression_array[1];
                }
                // 获得当前所有数据
                var array = this._dc_render_data_.data_fetched.all_data;
                var _dc_selected_items_ = [];
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    if (element._dc_select_) {
                        _dc_selected_items_.push(array[index]);
                    }
                }
                // 拆分小数点前后的值
                if (expression_array.length > 1) {
                    window[li_function.items.on_change_value]({
                        row_data: row_data,
                        index: index,
                        value: value,
                        expression_value: expression_value,
                        expression_int_value: expression_array[0],
                        expression_float_value: expression_array[1],
                    });
                } else {
                    window[li_function.items.on_change_value]({
                        row_data: row_data,
                        index: index,
                        value: value,
                        expression_value: expression_value,
                    });
                }
            }
        }
        // 选择之后计算数值
        render_somthing.prototype.func_check_counting = function (obj) {
            // 获得当前所有数据
            var array = this._dc_render_data_.data_fetched.all_data;
            var _dc_selected_items_ = [];
            for (let index = 0; index < array.length; index++) {
                const element = array[index];
                if (element._dc_select_) {
                    _dc_selected_items_.push(array[index]);
                }
            }
            return _dc_selected_items_;
        }
        // 深复制对象
        render_somthing.prototype.func_deep_clone_obj = function (obj) {
            if (!(typeof obj === 'object' && obj)) {
                return null;
            }
            var new_obj = Array.isArray(obj) ? [] : {};
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof obj[key] === 'obj' && obj[key]) {
                        new_obj[key] = deepClone(obj[key]);
                    } else {
                        new_obj[key] = obj[key];
                    }
                }
            }
            return new_obj;
        }
        // 获取指定时间离当前时间的值
        render_somthing.prototype.func_get_diff_date = function (dateTimeStamp) {
            var minute = 1000 * 60;
            var hour = minute * 60;
            var day = hour * 24;
            var halfamonth = day * 15;
            var month = day * 30;
            var now = new Date().getTime();
            dateTimeStamp = new Date(dateTimeStamp.replace(/-/g, "/"));
            var diffValue = now - dateTimeStamp;
            if (diffValue < 0) {
                diffValue = Math.abs(diffValue);
                var monthC = diffValue / month;
                var weekC = diffValue / (7 * day);
                var dayC = diffValue / day;
                var hourC = diffValue / hour;
                var minC = diffValue / minute;
                if (monthC >= 1) {
                    result = "" + parseInt(monthC) + "月后";
                } else if (weekC >= 1) {
                    result = "" + parseInt(weekC) + "周后";
                } else if (dayC >= 1) {
                    result = "" + parseInt(dayC) + "天后";
                } else if (hourC >= 1) {
                    result = "" + parseInt(hourC) + "小时后";
                } else if (minC >= 1) {
                    result = "" + parseInt(minC) + "分钟后";
                } else
                    result = "刚刚";
                return result;
            } else {
                var monthC = diffValue / month;
                var weekC = diffValue / (7 * day);
                var dayC = diffValue / day;
                var hourC = diffValue / hour;
                var minC = diffValue / minute;
                if (monthC >= 1) {
                    result = "" + parseInt(monthC) + "月前";
                } else if (weekC >= 1) {
                    result = "" + parseInt(weekC) + "周前";
                } else if (dayC >= 1) {
                    result = "" + parseInt(dayC) + "天前";
                } else if (hourC >= 1) {
                    result = "" + parseInt(hourC) + "小时前";
                } else if (minC >= 1) {
                    result = "" + parseInt(minC) + "分钟前";
                } else
                    result = "刚刚";
                return result;
            }
        }
        // 替换指定位置字符串
        render_somthing.prototype.func_mask_text = function (text, from, count, char) {
            var _text_ = "";
            for (let index = 0; index < count; index++) {
                _text_ += char;
            }
            return text.substr(0, from) + _text_ + text.substr(from + count, text.length - from - count);
        }

        // 格式化文件大小带单位的字符串
        render_somthing.prototype.func_get_file_formated_size = function (value, bit) {
            if (null == value || value == '') {
                return "0B";
            }
            var unitArr = new Array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
            var index = 0;
            var srcsize = parseFloat(value);
            index = Math.floor(Math.log(srcsize) / Math.log(1024));
            var size = srcsize / Math.pow(1024, index);
            size = size.toFixed(bit); //保留的小数位数
            return size + unitArr[index];
        }
    }

    // 初始化渲染器配置
    render_somthing.prototype.init = function (config) {
        window[`${config.id}_config`] = this;
        this.config = config;
        this.config.container.html = this.config.container.html ? this.config.container.html : `<div style="width:100%;height:100%;position: relative;overflow:auto;overflow-x:hidden;"></div>`
        $(this.config.id).html(this.config.container.html);

        // 当类型为瀑布流时
        if (this.config.method.type == "flow") {
            // 记录所有高度
            this.height_array = [];

            // 为容器添加固定的类
            $($(this.config.id).children()[0]).addClass(this.config.id.replace("#", "") + "_container");
            // 为容器内的渲染内容添加默认类
            var css = `.${this.config.id.replace("#", "")}_content {position: absolute;display: none;}`
            var style = document.createElement("style");
            style.appendChild(document.createTextNode(css));
            document.getElementsByTagName("head")[0].appendChild(style);
        }
        // 当类型为x
        if (this.config.method == "x") {
            // 记录所有高度
            this.height_array = [];

            // 为容器添加固定的类
            $($(this.config.id).children()[0]).addClass(this.config.id.replace("#", "") + "_container");
            // 为容器内的渲染内容添加默认类
            var css = `.${this.config.id.replace("#", "")}_content {position: absolute;display: none;}`
            var style = document.createElement("style");
            style.appendChild(document.createTextNode(css));
            document.getElementsByTagName("head")[0].appendChild(style);
        }
    }
    // 根据配置渲染数据
    render_somthing.prototype.render = function (data, type = "replace") {
        this.render_type = type;
        this.current_data = data;
        if (type == "replace") {
            this.all_data = data;
        }
        else if (type == "append") {
            this.all_data = this.all_data.concat(data);
        }
        this.content_html = "";
        this.row_html = "";

        for (let index = 0; index < this.current_data.length; index++) {
            this.row_html = this.config.content.default;
            var row_data = this.current_data[index];
            // 处理字段函数
            if (this.config.field_function) {
                for (let index = 0; index < this.config.field_function.length; index++) {
                    const element = this.config.field_function[index];
                    if (row_data[element.field]) {
                        try {
                            switch (element.type) {
                                case "item_amount":
                                    _temp_item_amount_ =
                                        `
<div li_function_index="${index}" key=${_dc_render_data_.id} index=${index} class="_dc_${_dc_render_data_.id}_counting_" type="-">${element.items.sub_html}</div>
<div index=${index} class="_dc_${_dc_render_data_.id}_counting_">${element.items.input_html}</div>
<div li_function_index="${index}" key=${_dc_render_data_.id} index=${index} class="_dc_${_dc_render_data_.id}_counting_" type="+">${element.items.plus_html}</div>`;
                                    break;
                                // 字段值为空时的处理
                                case "null_replace":
                                    if (row_data[element.field] == null || row_data[element.field] ==
                                        "") {
                                        row_data[element.field] = element.text;
                                    }
                                    break;
                                // 字段类型为日期型
                                case "format_datetime":
                                    if (element.format == "to-now") {
                                        // 获得到当前时间有多长
                                        row_data[element.field] = this.func_get_diff_date(row_data[element.field]);
                                    }
                                    break;
                                case "mask_text":
                                    row_data[element.field] = this.func_mask_text(row_data[element
                                        .field], element.from, element.to, element.char);
                                    break;
                                case "format_filesize":
                                    row_data[element.field] = this.func_get_file_formated_size(parseInt(
                                        row_data[element.field]), element.bit);
                                    break;
                                case "replace_text":
                                    row_data[element.field] = row_data[element.field].replace(element.text, element
                                        .replace_text)
                                    break;
                                case "format_search_keyword":
                                    // 获得搜索关键字
                                    keyword = $(`#_dc_${id}_search_input_`).val();
                                    if (keyword) {
                                        // 以用户设置的颜色重点标出该关键字
                                        row_data[element.field] = row_data[element.field].toString()
                                            .replace(eval("/" + keyword + "/"),
                                                `<a style='color:${element.color ? element.color : "red"}'>${keyword}</a>`
                                            );
                                    }
                                    break;
                            }
                        } catch (error) {
                            // 字段内容违规时的处理
                            row_data[element.field] = "";
                        }
                    }
                    else {
                        for (let _index = 0; _index < this.config.field_function.length; _index++) {
                            const _element = this.config.field_function[_index];
                            if (_element.type == "null_replace" && _element.field == element.field) {
                                // 字段没有内容时的处理
                                row_data[element.field] = _element.text;
                            }
                        }
                    }
                }
            }

            // 处理条件渲染
            if (this.config.condition) {
                // 获取所有条件渲染表达式
                var array = this.config.condition;
                for (let condition_index = 0; condition_index < array.length; condition_index++) {
                    // 获得渲染条件
                    const element = array[condition_index];
                    if (element.expression.indexOf("^") > -1) {
                        // 替换常量( ^{ROW_INDEX} 表示行的常量)
                        if (eval(element.expression.replace("^{ROW_INDEX}", "index"))) {
                            // 符合条件则使用该条件指定的html
                            this.row_html = element.html;
                        }
                    } else {
                        // 替换变量
                        if (eval(element.expression.replace(/#{/, "row_data['").replace(/}/, "']"))) {
                            // 符合条件则使用该条件指定的html
                            this.row_html = element.html;
                        }
                    }
                }
            }

            // 处理标签事件
            var tag_array = this.row_html.split("<");
            var tag_base_index = 0;
            // 追加模式时，设置index下标
            if (this.all_data.length > this.current_data.length) {
                tag_base_index = this.all_data.length - this.current_data.length;
            }
            for (let tag_index = 0; tag_index < tag_array.length; tag_index++) {
                const element = tag_array[tag_index];
                var attr_to_insert;
                if (element != "" && element.substring(0, 1) != "/") {
                    reg = />/;
                    // debugger;
                    attr_to_insert =
                        ` onclick="render_somthing_on_click(this,'${this.config.id}',${tag_base_index + index})"`
                    tag_array[tag_index] = element.replace(/>/, attr_to_insert + ">")
                }
            }
            this.row_html = tag_array.join("<");

            // 将html模板中的#{}替换为字段名
            for (var key in row_data) {
                var item = row_data[key];
                // 得到待替换的字段名
                re = new RegExp(`#{${key}}`, "g");
                this.row_html = this.row_html.replace(re, row_data[key]);
            }
            // 瀑布流时，添加类
            if (this.config.method.type == "flow") {
                this.row_html = `<div class="${this.config.id.replace("#", "")}_content">${this.row_html}</div>`
            }
            this.content_html = this.content_html + this.row_html;
        }

        // 往容器中添加本次渲染的所有行/块的内容
        if (type == "replace") {
            $($($(this.config.id)[0].children)).html(this.content_html);
        }
        else if (type == "append") {
            $($($(this.config.id)[0].children)).append(this.content_html);
            //追加之后实现瀑布流
            that.water_fall();
        }

        if (this.config.method.type == "flow") {
            that = this;
            // 页面尺寸改变时实时触发
            window.onresize = function () {
                //重新定义瀑布流
                that.water_fall();
            };
            //初始化
            window.onload = function () {
                //实现瀑布流
                that.water_fall();
            }
        }
    }

    render_somthing.prototype.water_fall = function (data) {
        //$('body').css('margin','0px');
        console.log($($(this.config.id)[0].children).children().length)
        // 1 确定图片的宽度 - 滚动条宽度
        var pageWidth = $("." + this.config.id.replace("#", "") + "_container").width();
        var itemWidth = parseInt((pageWidth - (this.config.method.column - 1) * this.config.method.gap) / this.config.method.column); //得到item的宽度
        $(`.${this.config.id.replace("#", "")}_content`).width(itemWidth); //设置到item的宽度
        // 获得已添加对象的数量
        var array = array = $("." + this.config.id.replace("#", "") + "_container").children();
        // 追加模式，则只需要后面的对象
        if (this.render_type != "replace") {
            var start = this.all_data.length - this.current_data.length;
            var end = this.current_data.length;
            array = $("." + this.config.id.replace("#", "") + "_container").children().splice(start, end);
        }
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            var height = $(element).height();
            // 第1行
            if (index < this.config.method.column && this.render_type == "replace") {
                $(element).css({
                    top: 0,
                    left: (itemWidth) * index + this.config.method.gap * index,
                    display: "block",
                });
                //将各元素行高push到数组
                this.height_array.push(height);
            }
            // 其它行
            else {
                // 找到数组中最小高度  和 它的索引
                var minHeight = this.height_array[0];
                var min_height_index = 0;
                for (var j = 0; j < this.height_array.length; j++) {
                    if (minHeight > this.height_array[j]) {
                        minHeight = this.height_array[j];
                        min_height_index = j;
                    }
                }
                // top值就是最小列的高度
                $(element).css({
                    top: this.height_array[min_height_index] + this.config.method.gap, //设置30的距离
                    left: $($("." + this.config.id.replace("#", "") + "_container").children()[min_height_index]).css("left"),
                    display: "block",
                });
                this.height_array[min_height_index] = this.height_array[min_height_index] + height + this.config.method.gap; //设置30的距离
            }
        }
    }
}

